package tools

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"regexp"
	"strconv"
)

func ParseNetPic(picLink string) (contentType string, body []byte, err error) {
	//t := time.Now()

	var resp *http.Response
	resp, err = http.Get(picLink)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	contentType = resp.Header.Get("Content-Type")
	body, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	//mlog.Log.Info("git wx net head pic, spend %dms", CalculationSpend(t, time.Now()))
	return
}

func GetPageWithC(pageStr, pageSizeStr string, tcnt int) (lim, off, page, total, pageSize int) {
	return GetPage(pageStr, pageSizeStr, tcnt)
}

func GetPage(pageStr, pageSizeStr string, tcnt int) (lim, off, page, total, pageSize int) {
	page, _ = strconv.Atoi(pageStr)
	pageSize, _ = strconv.Atoi(pageSizeStr)
	if page <= 0 || pageSize == 0 {
		return
	}
	total = tcnt / pageSize
	if tcnt%pageSize > 0 {
		total++
	}
	if tcnt < pageSize {
		pageSize = tcnt
	}
	if page > total {
		return
	}
	return pageSize, (page - 1) * pageSize, page, total, pageSize
}

func GetLookUidAndOtherUid(uuid, otherUUidStr string) (lookUid string, err error) {
	if otherUUidStr != "" {
		lookUid = otherUUidStr
	} else if uuid != "" {
		lookUid = uuid
	} else {
		err = errors.New("can't get lookUid, because haven't uid or otherUid")
	}
	return
}

// 正则过滤sql注入的方法
// 参数 : 要匹配的语句
func FilteredSQLInject(toMatchStr string) bool {
	//过滤 ‘
	//ORACLE 注解 --  /**/
	//关键字过滤 update ,delete
	// 正则的字符串, 不能用 " " 因为" "里面的内容会转义
	str := `(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|(\b(select|update|and|or|delete|insert|trancate|char|chr|into|substr|ascii|declare|exec|count|master|into|drop|execute)\b)`
	re, err := regexp.Compile(str)
	if err != nil {
		panic(err.Error())
		return false
	}
	return re.MatchString(toMatchStr)
}

func BindJson(body io.ReadCloser, retMap interface{}) error {
	bodybuf, err := ioutil.ReadAll(body)
	if err != nil {
		return err
	}
	json.Unmarshal(bodybuf, &retMap)
	return nil
}

//func DeletePhotoStoryWithAliyun(uuid string, link string, tx *db.Tx) (err error) {
//	err = aliyun.DeleteObject(link)
//	if err != nil {
//		return
//	}
//	result, err := tx.Exec(`DELETE FROM photo_story WHERE uuid = ? AND link = ?`, uuid, link)
//	if err != nil {
//		return
//	}
//	if rowsAffected, _ := result.RowsAffected(); rowsAffected == 0 {
//		err = fmt.Errorf("%s delete file failed, when delete photo_story table", uuid)
//		return
//	}
//	return nil
//}
